package com.zenithsun.news.newsinfo.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.syzg.base.login.model.LoginObject;
import com.syzg.base.merge.model.Person;
import com.syzg.base.person.dao.PersonDAO;
import com.syzg.common.service.impl.BaseServiceImpl;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SearchMap;
import com.syzg.core.exception.ServiceException;
import com.syzg.core.page.DefaultPageResult;
import com.syzg.core.page.PageResult;
import com.syzg.core.util.SecurityUtil;
import com.syzg.core.util.StringUtil;
import com.syzg.solr.SolrManage;
import com.zenithsun.common.bean.ModelType;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.bean.SolrSearch;
import com.zenithsun.common.image.ImageCut;
import com.zenithsun.common.image.StorageRule;
import com.zenithsun.common.review.dao.ReviewDAO;
import com.zenithsun.common.review.model.Review;
import com.zenithsun.common.review.model.ReviewState;
import com.zenithsun.common.util.RegExUtil;
import com.zenithsun.common.util.image.ImageInfo;
import com.zenithsun.common.util.image.ImageSize;
import com.zenithsun.common.util.image.ImageUtils;
import com.zenithsun.news.newsinfo.dao.NewsdetailinfoDAO;
import com.zenithsun.news.newsinfo.dao.NewsinfoDAO;
import com.zenithsun.news.newsinfo.model.NewsSolrSearch;
import com.zenithsun.news.newsinfo.model.Newsdetailinfo;
import com.zenithsun.news.newsinfo.model.Newsinfo;
import com.zenithsun.news.newsinfo.service.NewsinfoService;
import com.zenithsun.news.solr.model.NewsInfo;
import com.zenithsun.news.solr.util.SolrHelper;
import com.zenithsun.news.specialnews.model.Specialnews;

@Service("newsinfoService")
public class NewsinfoServiceImpl extends BaseServiceImpl<Newsinfo> implements NewsinfoService {

	private NewsinfoDAO newsinfoDAO = null;

	@Resource
	private ReviewDAO reviewDao = null;

	@Resource
	private NewsdetailinfoDAO newsdetailinfoDao = null;

	@Resource
	private PersonDAO personDAO=null;
	
	@Resource
	public void setNewsinfoDAO(NewsinfoDAO newsinfoDAO) {
		this.setDAO(newsinfoDAO);
		this.newsinfoDAO = newsinfoDAO;
	}

	@Override
	public void delNewsinfo(String[] ids) throws ServiceException {
		//TODO 图片资源未删除
		newsinfoDAO.delNewsdetailinfoBatch(ids);
		newsinfoDAO.deleteNewsinfoBatchSolr(ids);
		
		//同步删除索引库
		SolrHelper.getInstance().delete(ids);
		
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PageResult queryNewsinfo(int pageNo, int pageSize,
			Newsinfo searchCondition) throws Exception {
		int totalCount = this.newsinfoDAO.countNewsinfo(searchCondition, -1);
		List items = this.newsinfoDAO.listNewsinfo(pageNo, pageSize,searchCondition, -1);
		PageResult pageResult = new DefaultPageResult(items, totalCount,(pageNo - 1) * pageSize, pageSize);
		return pageResult;
	}

	@Override
	public Newsinfo getFullNewsinfoById(String id) throws Exception {
		Newsinfo newsinfo = this.newsinfoDAO.findNewsinfoById(id);
		if (newsinfo != null) {
			newsinfo.setNewsdetails(this.newsdetailinfoDao
					.listNewsdetailinfo(id));
		}
		return newsinfo;
	}

	@Override
	public int saveNewsdetailinfoBatch(List<Newsdetailinfo> list)
			throws Exception {
		if (list != null) {
			this.newsdetailinfoDao.saveNewsdetailinfoBatch(list);
		}
		return list.size();
	}

	/**
	 * 获取图片集合的Map
	 * 
	 * @param remark
	 * @return Map<String,Newsdetailinfo>
	 */
	private Map<String, Newsdetailinfo> getNewsdetailinfoMap(String remark) {
		if (StringUtils.isBlank(remark)) {
			return null;
		}
		Map<String, Newsdetailinfo> map = new HashMap<String, Newsdetailinfo>();
		List<Newsdetailinfo> list = JSON.parseArray(remark,
				Newsdetailinfo.class);
		for (Newsdetailinfo item : list) {
			map.put(item.getPath(), item);
		}
		return map;
	}

	@Override
	public boolean addNewsInfo(Newsinfo newsinfo, String type,boolean isReview, HttpServletRequest request) throws Exception {
		boolean flag = false;
		if (newsinfo == null) {
			return flag;
		}
		newsinfo.setId(PKCreator.getPk());
		// LoginObject loginObj = SystemUtil.getLoginObject();
		// newsinfo.setEditor(loginObj.getPersonName());
		newsinfo.setCreateTime(new Date());
		newsinfo.setUpdateTime(newsinfo.getCreateTime());
		/*
		 * 初始化规则，获取正式存储目录，临时目录在初始化页面时 已经产生，并存储在newsinfo.getPicTempPath()中，
		 * 保存数据时将临时图片存储转为正式存储即可。
		 */
		StorageRule sr = new StorageRule(request);
		Map<String, Newsdetailinfo> map = getNewsdetailinfoMap(newsinfo.getRemark());
		// 设置空值
		newsinfo.setRemark(null);
		newsinfo.setNewsTypeId("通讯");
		if ("pic".equals(type)) {
			newsinfo.setType("pic");
			this.create(newsinfo);
			sr.setTempStore(false);
			File file = new File(newsinfo.getPicTempPath());
			File[] picList = file.listFiles();
			if (picList != null) {
				for (File f : picList) {
					String shortPath = f.getAbsolutePath().replaceAll("\\\\","/");
					shortPath = shortPath.replace((sr.getCurrProjectPath()).replaceAll("\\\\", "/"),"");
					sr.setFileName(f.getName());
					String savePath = sr.GetNewsImageStorePath();
					FileCopyUtils.copy(f, new File(savePath));
					// 生成不同尺寸的图片
					Newsdetailinfo newsdetailinfo = map.get(shortPath);
					if (newsdetailinfo == null) {
						newsdetailinfo = new Newsdetailinfo();
						newsdetailinfo.setId(PKCreator.getPk());
					}
					String imageSavePath = (sr.getCurrProjectPath() + StorageRule.newsSavePath).replaceAll("\\\\", "/");
					savePath = savePath.replaceAll(imageSavePath, "");
					//设置新的存储地址
					newsdetailinfo.setPath("/" + savePath);
					newsdetailinfo.setNewsinfo(newsinfo);
					newsdetailinfoDao.create(newsdetailinfo);
					//createThumbnail(sr,mpf.getBytes());
				}
				// 删除临时目录
				com.zenithsun.common.util.FileUtil.deleteDir(file);
				flag = true;
			} else {
				// 不一定会上传文件，所以此处应返回true
				flag = true;
			}
		} else {
			newsinfo.setType("word");
			this.create(newsinfo);
			flag = true;
		}
		// 增加审核信息
		this.addReview(newsinfo, isReview);
		//刷新全文索引内容
		//SolrManage.dataIncrementImport();
		SolrHelper.getInstance().insert(new NewsInfo(newsinfo));
		return flag;
	}

	/**
	 * 生成不同尺寸的缩略图
	 * 
	 * @param sr
	 */
	private void createThumbnail(StorageRule sr) throws Exception {
		// 生成不同尺寸的图片
		String sourceUrl = sr.GetNewsImageStorePath();
		String fileType = sourceUrl.substring(sourceUrl.lastIndexOf("."));
		String targetUrl = sourceUrl.substring(0, sourceUrl.lastIndexOf("."));
		List<ImageSize> imageList = ImageSize.GetThumbnailList();
		for (ImageSize imageSize : imageList) {
			ImageCut.createImageBySize(sourceUrl,
					targetUrl + "_" + imageSize.getWidth() + fileType,
					imageSize.getWidth(), imageSize.getHeight());
		}
	}

	/**
	 * 生成不同尺寸的缩略图
	 * 
	 * @param sr
	 */
	private void createThumbnail(StorageRule sr,byte[] bs) throws Exception {
		// 生成不同尺寸的图片
		String sourceUrl = sr.GetNewsImageStorePath();
		String fileType = sourceUrl.substring(sourceUrl.lastIndexOf("."));
		String targetUrl = sourceUrl.substring(0, sourceUrl.lastIndexOf("."));
		List<ImageSize> imageList = ImageSize.GetThumbnailList();
		for (ImageSize imageSize : imageList) {
			//ImageCut.createImageBySize(sourceUrl,targetUrl + "_" + imageSize.getWidth() + fileType,imageSize.getWidth(), imageSize.getHeight());
			ImageCut.createImageBySize(bs,targetUrl + "_" + imageSize.getWidth() + fileType,imageSize);
		}
	}
	
	/**
	 * 增加审批信息
	 * 
	 * @param newsinfo
	 * @param isReview
	 * @return boolean
	 */
	private boolean addReview(Newsinfo newsinfo, boolean isReview) {
		try {
			Review review = new Review();
			review.setBusId(newsinfo.getId());
			review.setBusMark(ModelType.News.toString());
			review.setCreateTime(new Date());
			review.setId(PKCreator.getPk());
			review.setMark(Short.valueOf("0"));
			if (isReview) {
				review.setState(ReviewState.WaitReview.toShort());
			} else {
				review.setState(ReviewState.SaveNotReview.toShort());
			}
			reviewDao.create(review);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 1：通过正则表达式获取内容中的图片标签<br/>
	 * 2：该方法只对编辑新闻时适用，对新闻编辑前后内容的图片进行提取后分析
	 * 
	 * @return
	 */
	public void deleteSurplusImageFromContentByReg(HttpServletRequest request,String newContent, String oldContent) {
		if(StringUtils.isBlank(oldContent)){
			return;
		}
		List<String> oldImageList =null;
		List<String> newImageList =null;
		if(StringUtils.isBlank(newContent)){
			newImageList=new ArrayList<String>();
		}else{
			oldImageList = RegExUtil.getImageFromContentByReg(oldContent);
			newImageList = RegExUtil.getImageFromContentByReg(newContent);
		}
		if(oldImageList==null||oldImageList.size()==0){
			return;
		}
		StorageRule sr = new StorageRule(request);
		String storePath = sr.getCurrProjectPath().replaceAll(request.getContextPath(), "");
		for (String path : oldImageList) {
			if (newImageList.contains(path)) {
				File file = new File(storePath + path);
				file.delete();
			}
		}
	}

	@Override
	public List<Newsdetailinfo> listImage(String newsinfoId,
			String picTempPath, HttpServletRequest request) throws Exception {
		StorageRule sr = new StorageRule(request);
		/*
		 * 根据新闻ID判断新闻是否入库，如果未入库，图片保存在临时文件夹下，会定时清理， 入库则直接将图片保存在正式地址
		 */
		if (StringUtil.isEmpty(newsinfoId) || newsinfoId.equals("null")) {
			// 临时地址
			// 获取在HTTP上的访问路径
			String path = sr.GetCurrProjectPathHttpPath(picTempPath);
			List<Newsdetailinfo> lstNewsdetailinfo = new ArrayList<Newsdetailinfo>();
			File file = new File(picTempPath);
			File[] picList = file.listFiles();
			if (picList != null && picList.length > 0) {
				for (File f : picList) {
					Newsdetailinfo newsdetailinfo = new Newsdetailinfo();
					newsdetailinfo.setId(PKCreator.getPk());
					newsdetailinfo.setPath(path + File.separator + f.getName());
					newsdetailinfo.setPath(newsdetailinfo.getPath().replaceAll(
							"\\\\", "/"));
					lstNewsdetailinfo.add(newsdetailinfo);
				}
			}
			return lstNewsdetailinfo;
		} else {
			// 正式地址
			SearchMap searchMap = SearchMap.forClass(Newsdetailinfo.class);
			searchMap.eq("a.newsinfo.id", newsinfoId);
			searchMap.addOrder("a.orderNo", searchMap.ORDER_ASC);
			List<Newsdetailinfo> lstNewsdetailinfo = this.findObjects(searchMap);
			for (Newsdetailinfo detail : lstNewsdetailinfo) {
				detail.setPath(sr.GetNewsImageShowPath() + File.separator
						+ detail.getPath());
				detail.setPath(detail.getPath().replaceAll("\\\\", "/"));
			}
			return lstNewsdetailinfo;
		}
	}

	@Override
	public OutMessage uploadImageToPicNews(HttpServletRequest request,
			String newsinfoId, String picTempPath) throws Exception {
		OutMessage outMessage = new OutMessage();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> itr = multiRequest.getFileNames();
			if (!itr.hasNext()) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			}
			MultipartFile mpf = null;
			Newsinfo newsinfo = new Newsinfo();
			newsinfo.setId(newsinfoId);
			// List<Newsdetailinfo> piclist = new ArrayList<Newsdetailinfo>();
			try {
				String saveStoreFolder = null;
				// 加载文件存储规则
				StorageRule sr = new StorageRule(request);
				while (itr.hasNext()) {
					mpf = multiRequest.getFile(itr.next());
					sr.setFileName(mpf.getOriginalFilename());
					if (StringUtil.isNotBlank(newsinfoId)
							&& !"null".equals(newsinfoId)) {
						sr.setTempStore(false);
						saveStoreFolder = sr.GetNewsImageStorePath();
					} else {
						sr.setTempStore(true);
						if(null==sr.getUUIDFileName()){
						saveStoreFolder = picTempPath
								+ File.separator
								+ StorageRule.creatUUIDName(mpf
										.getOriginalFilename());
						}else{
							saveStoreFolder = picTempPath
									+ File.separator
									+ sr.getUUIDFileName();
						}
					}
					File file = new File(saveStoreFolder);
					// 存储文件的目录是否存在，不存在则创建，否则会导致上传失败
					if (!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					//FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(file));
					ImageCut.createAddWater(mpf.getBytes(),file);
					createThumbnail(sr,mpf.getBytes());
				}
				Newsdetailinfo newsdetailinfo = getNewsdetailinfo(mpf, sr,
						saveStoreFolder);
				if (StringUtil.isNotBlank(newsinfoId)
						&& !"null".equals(newsinfoId)) {
					// 将图片详情数据存储到数据库中
					newsdetailinfo.setNewsinfo(newsinfo);
					// piclist.add(newsdetailinfo);
					this.create(newsdetailinfo);
				} else {
					// 存入outMessage的content属性是为了返回放置在前端的newsinfo的remark属性中，在用户保存的时候回传。
					outMessage.setContent(newsdetailinfo);
				}
				// newsinfoService.saveNewsdetailinfoBatch(piclist);
			} catch (IOException e) {
				e.printStackTrace();
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
				// e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
				// e.printStackTrace();
			}
		}
		outMessage.setState(OutMessageState.Success);
		return outMessage;
	}

	/**
	 * 获取图片详情数据
	 * 
	 * @param mpf
	 * @param sr
	 * @return
	 * @throws Exception
	 */
	private Newsdetailinfo getNewsdetailinfo(MultipartFile mpf, StorageRule sr,
			String saveStoreFolder) throws Exception {
		// 将图片详情数据存储到数据库中
		Newsdetailinfo newsdetailinfo = new Newsdetailinfo();
		if (mpf != null) {
			ImageInfo imageInfo = new ImageInfo();
			imageInfo.setRemark(mpf.getOriginalFilename().substring(0,
					mpf.getOriginalFilename().lastIndexOf(".")));
			imageInfo.loadImgInfo(mpf.getBytes());
			newsdetailinfo.setRemark(imageInfo.getRemark());
			newsdetailinfo.setArtist(imageInfo.getArtist());
			newsdetailinfo.setShootingTime(imageInfo.getShootDateTime());
		}
		// 将图片详情数据存储到数据库中
		newsdetailinfo.setId(PKCreator.getPk());
		if (sr.isTempStore()) {
			newsdetailinfo.setPath((saveStoreFolder).replaceAll(
					sr.getCurrProjectPath(), "").replaceAll("\\\\", "/"));
		} else {
			newsdetailinfo.setPath(sr.getRelativeStorePath());
		}
		return newsdetailinfo;
	}

	@Override
	public boolean saveReview(Newsinfo newsinfo, boolean isReview)
			throws Exception {
		Review review = this.reviewDao.getReviewByBus(newsinfo.getId(),
				ModelType.News.toString());
		if (review == null) {
			return addReview(newsinfo, isReview);
		} else {
			if (isReview) {
				review.setState(ReviewState.WaitReview.toShort());
				this.reviewDao.update(review);
			}
			return true;
		}
	}

	@Override
	public OutMessage cutCover(String newId, int width, int height, int px_1,
			int py_1, int px_2, int py_2, HttpServletRequest request)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		// 查询当前新闻的新闻，获取封面图片的地址
		String storeUrl = "";
		StorageRule sr = new StorageRule(request);
		if (!"null".equals(newId) && StringUtil.isNotEmpty(newId)) {
			// 编辑
			Newsinfo news = this.newsinfoDAO.findNewsinfoById(newId);
			sr.setFileName(news.getCoverPath());
			String sourceUrl = sr.getCurrProjectPath() + news.getCoverPath();
			String targetUrl = sr.GetNewsImageStorePath();
			// 剪切图片，并存入新地址
			ImageCut.cut(sourceUrl, targetUrl, width, height, px_1, py_1, px_2,
					py_2);
			storeUrl = StorageRule.newsSavePath + sr.getRelativeStorePath();
			// 修改新闻封面信息
			this.newsinfoDAO.updateCover(newId, storeUrl);
		} else {
			// 添加
			String coverPath = request.getParameter("coverPath");
			sr.setFileName(coverPath);
			String sourceUrl = sr.getCurrProjectPath() + coverPath;
			String targetUrl = sr.GetNewsImageStorePath();
			// 剪切图片，并存入新地址
			ImageCut.cutAndWater(sourceUrl, targetUrl, width, height, px_1, py_1, px_2,py_2);
			storeUrl = StorageRule.newsSavePath + sr.getRelativeStorePath();
		}

		// 查询的分页数据存入到统一输出对象的内容属性中
		outMessage.setContent(storeUrl);
		outMessage.setState(OutMessageState.Success);
		return outMessage;
	}

	@Override
	public OutMessage uploadCover(String newId, HttpServletRequest request)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> itr = multiRequest.getFileNames();
			if (!itr.hasNext()) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			}
			try {
				// 加载文件存储规则
				StorageRule sr = new StorageRule(request);
				sr.setTempStore(false);
				// 设置当前项目实际存储路径
				MultipartFile mpf = null;
				while (itr.hasNext()) {
					mpf = multiRequest.getFile(itr.next());
					sr.setFileName(mpf.getOriginalFilename());
					File file = new File(sr.GetNewsImageStorePath());
					// 存储文件的目录是否存在，不存在则创建，否则会导致上传失败
					if (!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					// FileCopyUtils.copy(mpf.getBytes(),new
					// FileOutputStream(file));
					//Thumbnails.of(mpf.getInputStream()).width(750).toFile(file);
					ImageCut.createAddWater(mpf.getBytes(), file,750);
					
					// newId不为空，修改
					if (StringUtil.isNotEmpty(newId)) {
						this.newsinfoDAO.updateCover(
								newId,
								StorageRule.newsSavePath
										+ sr.getRelativeStorePath());
					}

					outMessage.setState(OutMessageState.Success);
					outMessage.setContent(StorageRule.newsSavePath
							+ sr.getRelativeStorePath());
				}
			} catch (IOException e) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			} catch (Exception e) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			}
		}
		return outMessage;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public PageResult queryNewsinfoPublished(int pageNo, int pageSize,Newsinfo searchCondition) throws Exception {
		int totalCount = this.newsinfoDAO.countNewsinfo(searchCondition,ReviewState.ReviewSuccess.toShort());
		List items = this.newsinfoDAO.listNewsinfo(pageNo, pageSize,searchCondition, ReviewState.ReviewSuccess.toShort());
		List newItems = new ArrayList<>();
		//处理图片,不存在替换
		for (int i = 0; i < items.size(); i++) {
			Newsinfo n = (Newsinfo)items.get(i);
			n.setCoverPath(ImageUtils.getInstance().srcCheckAndDefault(n.getCoverPath()));
			newItems.add(n);
		}
		PageResult pageResult = new DefaultPageResult(newItems, totalCount,(pageNo - 1) * pageSize, pageSize);
		return pageResult;
	}

	@Override
	public Newsinfo findNewsinfoById(String newsId) throws Exception {
		return this.newsinfoDAO.findNewsinfoById(newsId);
	}
/*
 * 后台的新闻编剧栏目的查询
 */
	@Override
	public PageResult queryNewsinfoSolr(int pageNo, int pageSize,Newsinfo searchCondition) throws Exception {
		SolrSearch<Newsinfo> solrSearch=new NewsSolrSearch(searchCondition,(pageNo-1)*pageSize,pageSize,true);
		QueryResponse qr = SolrManage.Search(solrSearch);
		SolrDocumentList docs = qr.getResults();
		List<String> lstIds = new ArrayList<String>();
		for (SolrDocument doc : docs) {
			lstIds.add(String.valueOf(doc.getFieldValue("id")));
		}
		List list=this.newsinfoDAO.listNewsinfo(lstIds);
		PageResult pageResult = new DefaultPageResult(list, docs.getNumFound(),Integer.valueOf((pageNo - 1) * pageSize).longValue(), pageSize);
		return pageResult;
	}
	
	/*
	 * 首页的查询高亮
	 */
	@Override
	public PageResult queryNewsinfoSolrTwo(int pageNo, int pageSize,Newsinfo searchCondition) throws Exception {
		SolrSearch<Newsinfo> solrSearch=new NewsSolrSearch(searchCondition,(pageNo-1)*pageSize,pageSize,true);
		QueryResponse qr = SolrManage.Search(solrSearch);
		List list = new SolrDocumentList();
		SolrDocument doc = null;
		SolrDocumentList docs = qr.getResults();
		Map<String,Map<String,List<String>>> highlightMap = qr.getHighlighting();
		for(int i=0;i<docs.size();i++){
			doc=docs.get(i);
			if(highlightMap.get(doc.getFieldValue("id")).get("title_mmseg4j") != null)
				doc.setField("title_mmseg4j", highlightMap.get(doc.getFieldValue("id")).get("title_mmseg4j"));
			if(highlightMap.get(doc.getFieldValue("id")).get("content_mmseg4j") != null)
				doc.setField("content_mmseg4j", highlightMap.get(doc.getFieldValue("id")).get("content_mmseg4j"));
			
			if(highlightMap.get(doc.getFieldValue("id")).get("nabstract_mmseg4j") != null)
				doc.setField("nabstract_mmseg4j", highlightMap.get(doc.getFieldValue("id")).get("nabstract_mmseg4j"));
			
			if(highlightMap.get(doc.getFieldValue("id")).get("publishGroup_mmseg4j") != null)
				doc.setField("publishGroup_mmseg4j", highlightMap.get(doc.getFieldValue("id")).get("publishGroup_mmseg4j"));
			
			if(highlightMap.get(doc.getFieldValue("id")).get("keyword_mmseg4j") != null)
				doc.setField("keyword_mmseg4j_2", highlightMap.get(doc.getFieldValue("id")).get("keyword_mmseg4j"));
			else
				doc.setField("keyword_mmseg4j_2", doc.get("keyword_mmseg4j"));
			list.add(doc);
		}
		PageResult pageResult = new DefaultPageResult(list, docs.getNumFound(),Integer.valueOf((pageNo - 1) * pageSize).longValue(), pageSize);
		return pageResult;
	}
	/**
	 * 首页轮播
	 * @param rows 条数
	 * @return
	 * @throws Exception
	 */
	public List<HashMap<String, Object>> listNewsinfo_carousel(int rows)
			throws Exception {
		// TODO 轮播新闻
		List<HashMap<String, Object>> new_map = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> old_map = newsinfoDAO.listNewsinfo_carousel(rows);
		HashMap<String, Object> map = new HashMap<String, Object>();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < old_map.size(); i++) {
			map = old_map.get(i); 
			String publishTime = map.get("publish_time").toString();
        	Date newsDate = df.parse(publishTime);
        	long diff = new Date().getTime() - newsDate.getTime();
        	String dateStr = "";
        	long day=diff/(24*60*60*1000);
        	long hour=(diff/(60*60*1000)-day*24);
        	long min=((diff/(60*1000))-day*24*60-hour*60);
        	if(day > 0)
        	{
        		dateStr = day + "天";
        	}else{
        		if(hour > 0){ dateStr = hour + "小时";}else{dateStr = min + "分钟";}
        	}
        	map.put("diff_time", dateStr+"前");
        	new_map.add(map);
		}
		return new_map;
	}

	/**
	 * 置顶新闻
	 * @param rows 条数
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<HashMap<String, Object>> listNewsinfo_top(int rows)throws Exception {
		return newsinfoDAO.listNewsinfo_top(rows);
	}
	/**
	 * 按主题查找新闻
	 * @param rows 行数
	 * @param columnId 主题ID
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<HashMap<String, Object>> listNewsinfo_columns(int rows,String columnId) throws Exception {
		return newsinfoDAO.listNewsinfo_columns(rows, columnId);
	}
	/**
	 * 最新新闻
	 * @param rows 行数
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<HashMap<String, Object>> listNewsinfo_upToDate(int rows)throws Exception {
		return newsinfoDAO.listNewsinfo_upToDate(rows);
	}

	@Override
	public boolean modifyNewsInfo(boolean isReview, String id,Newsinfo newsinfoVO,HttpServletRequest request) throws Exception {
		try{
			Newsinfo newsinfo = findNewsinfoById(id);
			if (newsinfoVO.getIsTop() == null) {
				newsinfoVO.setIsTop((short) 0);
			}
			if (newsinfoVO.getIsCarousel() == null) {
				newsinfoVO.setIsCarousel((short) 0);
			}
			if (newsinfoVO.getIsStriking() == null) {
				newsinfoVO.setIsStriking((short) 0);
			}
			String oldContent=newsinfo.getContent();
			String newContent=newsinfoVO.getContent();
			newsinfo = (Newsinfo) MethodUtil.copyProperties(newsinfo,newsinfoVO);
			newsinfo.setUpdateTime(new Date());
			update(newsinfo);
			//保存和更新信息
			saveReview(newsinfo, isReview);
			//删除多余的图片
			deleteSurplusImageFromContentByReg(request,newContent, oldContent);
			//更新增量数据
			//SolrManage.dataIncrementImport();
			SolrHelper.getInstance().insert(new NewsInfo(newsinfoVO));
			return true;
		}catch(Exception e){
			return false;
		}
	}

	@Override
	public OutMessage mobileLogin(String userName, String password) throws Exception {
		Person person=personDAO.findPerson(userName, SecurityUtil.md5Hex(password));
		OutMessage outMessage=new OutMessage();
		if(person==null){
			outMessage.setState(OutMessageState.Fail);
			outMessage.setContent("没有找到该用户");
		}else{
			LoginObject loginObject = new LoginObject();
	        loginObject.setPersonId(String.valueOf(person.getId()));
	        loginObject.setPersonName(person.getName());
	        loginObject.setLogin(person.getAccount());
	    	outMessage.setState(OutMessageState.Success);
			outMessage.setContent(loginObject);
		}
		return outMessage;
	}

	/**
	 * 获取最新发布的新闻
	 * @param  limit 限制的条数
	 * @return 新闻集合
	 * @throws Exception
	 * */
	@Override
	public List<Newsinfo> getLatestPublishNews(int limit){
		return newsinfoDAO.getLatestPublishNews(limit);
	}

	/**
	 * 随机获取一条id不相等的图片新闻id
	 * @param  id 需要过滤的图片id
	 * @return 新闻id
	 * @throws Exception
	 * */
	@Override
	public String getRandomNewsinfo(String id){
		return newsinfoDAO.getRandomNewsinfo(id);
	}
	
	/**
	 * 根据栏目id获取发布的新闻的数量
	 * @param  columnid 栏目的id
	 * @return 新闻的数量
	 * @throws Exception
	 * */
	@Override
	public int getPublishNewsCountByColumnid(String columnid){
		return newsinfoDAO.getPublishNewsCountByColumnid(columnid);
	}
	
	/**
	 * 根据栏目id获取发布的新闻
	 * @param  pageNo 页码
	 * @param  limit 每页大小
	 * @param  columnid 栏目的id
	 * @return 新闻集合
	 * @throws Exception
	 * */
	@Override
	public List<Newsinfo> getPublishNewsByColumnid(int pageNo,int limit,String columnid){
		return newsinfoDAO.getPublishNewsByColumnid(pageNo, limit, columnid);
	}
	
	@Override
	public List<Newsdetailinfo> listImage(String newsinfoId) throws Exception {
		// TODO Auto-generated method stub
		return newsdetailinfoDao.listNewsdetailinfo(newsinfoId);
	}
	
	@Override
	public int updateSortsNewsdetailinfoBatch(List<Newsdetailinfo> list)
			throws Exception {
		// TODO Auto-generated method stub
		return newsdetailinfoDao.updateSortsNewsdetailinfoBatch(list);
	}
	/**
	 * 根据批量ID查询
	 * @param ids
	 * @return
	 */
	@Override
	public List<Newsinfo> getNewsInIds(String[] ids,boolean isNull) {
		// TODO Auto-generated method stub
		return newsinfoDAO.getNewsInIds(ids,isNull);
	}
	/**
	 * 专题ID查询新闻
	 * @param snId
	 * @return
	 */
	@Override
	public List<Newsinfo> getNewsBySNID(String snId) {
		// TODO Auto-generated method stub
		return newsinfoDAO.getNewsBySNID(snId);
	}
	
	@Override
	public PageResult queryNewsIsNotSpecial(int pageNo, int pageSize,Newsinfo searchCondition)
			throws Exception {
		// TODO Auto-generated method stub
		int totalCount = this.newsinfoDAO.getNewsCountBySnIdIsNotNull(searchCondition);
		List items = this.newsinfoDAO.getNewsListBySnIdIsNotNull(pageNo, pageSize,searchCondition);
		PageResult pageResult = new DefaultPageResult(items, totalCount,(pageNo - 1) * pageSize, pageSize);
		return pageResult;
	}
	
@Override
public List<HashMap<String, Object>> getSpecialNewsUpToDate(int rows) {
	// TODO Auto-generated method stub
	return newsinfoDAO.getSpecialNewsUpToDate(rows);
}
@Override
public List<Specialnews> getSpecialNews(){
	return newsinfoDAO.getSpecialNews();
}

@Override
public void delNewsinfoDetail(String[] ids,HttpServletRequest request) throws ServiceException {
	for(String id:ids){
		String[] idsp=id.split("\\|");
		newsinfoDAO.delNewsdetailinfo(idsp[0]);
		StorageRule sr = new StorageRule(request);
		sr.setFileName(idsp[1]);
		String path=sr.GetPicImageStorePath();
		System.out.println(path);
		new File(path).delete();
	}
}
}